<template>
  <div>
    <!-- 面包屑导航 -->
    <div class="center-w">
      <el-tabs v-model="activeName" type="card" @tab-click="tabClick">
        <el-tab-pane label="订单金额报表" name="first"></el-tab-pane>
        <el-tab-pane label="检测项目报表" name="second"></el-tab-pane>
        <el-tab-pane label="公众号关注人数" name="third"></el-tab-pane>
      </el-tabs>

      <div class="report">
        <!-- 年度、季度、月度标签 -->
        <div style="margin-bottom: 10px;" v-if="currentName != 'third'">
          <el-card shadow="always" :body-style="{ padding: '5px' }">
            <div class="header">
              <el-tag
                effect="dark"
                :disable-transitions="true"
                v-for="(item, index) in btnList"
                :key="index"
                @click="switchReport(index)"
                :type="currentType == index ? 'danger' : ''"
                >{{ item }}</el-tag
              >
            </div>
          </el-card>
        </div>
        <!-- 折线图搜索栏 -->
        <div style="margin-bottom: 10px;" v-show="currentName != 'third'">
          <el-card shadow="always" :body-style="{ padding: '20px' }">
            <div class="selectTop">
              <div style="width:50px;font-size: 14px;">年份：</div>
              <el-date-picker
                v-model="form.year"
                size="small"
                type="year"
                placeholder="选择年"
                value-format="yyyy"
              ></el-date-picker>
              <div
                style="width:50px;margin-left:10px;font-size: 14px;"
                v-if="form.dateType == 2"
              >
                月份：
              </div>
              <el-date-picker
                v-model="form.dateTimeFor"
                type="month"
                placeholder="选择月"
                size="small"
                value-format="M"
                format="M"
                v-if="form.dateType == 2"
              ></el-date-picker>
              <div style="width:50px;margin-left:10px;font-size: 14px;">
                公司：
              </div>
              <el-select
                ref="companyRef"
                @change="getUserName(1)"
                v-model="form.companyId"
                placeholder="请选择"
                style="padding-right:15px"
                size="small"
              >
                <el-option
                  v-for="item in companyId"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <div style="width:50px;font-size: 14px;">标签：</div>
              <el-select
                ref="tagRef"
                @change="getUserName(2)"
                v-model="form.lableId"
                placeholder="请选择"
                size="small"
                style="padding-right:15px"
              >
                <el-option
                  v-for="item in lableId"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <!-- 用户 -->
              <div style="width:50px;font-size: 14px;">用户：</div>
              <el-select
                ref="userRef"
                v-model="form.userId"
                @change="getUserName(3)"
                size="small"
                filterable
                :filter-method="remoteMethod"
                :loading="loading"
                placeholder="请选择"
                style="padding-right:15px"
              >
                <el-option
                  v-for="item in userIds"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </el-card>
        </div>
        <!-- 折线图、表格 -->
        <el-card
          shadow="always"
          :body-style="{ padding: '20px' }"
          v-show="currentName != 'third'"
        >
          <div class="part">
            <!-- echarts绑定dom -->
            <div class="main" id="main"></div>
          </div>
          <table
            v-if="currentType != 2 && activeName == 'first'"
            class="table11_3"
            align="center"
          >
            <tr>
              <th align="center" valign="middle"></th>
              <th
                v-for="(tr, index) in list"
                :key="index"
                align="center"
                valign="middle"
              >
                {{ tr.item1 }}
              </th>
            </tr>
            <tr>
              <td>
                订单金额
              </td>
              <td
                v-for="(tr, index) in list"
                :key="index"
                align="center"
                valign="middle"
              >
                {{ tr.item2 }}
              </td>
            </tr>
            <tr>
              <td>
                订单数量
              </td>
              <td
                v-for="(tr, index) in list"
                :key="index"
                align="center"
                valign="middle"
              >
                {{ tr.item3 }}
              </td>
            </tr>
          </table>

          <table
            v-if="currentType != 2 && activeName != 'first'"
            class="table11_3"
            align="center"
          >
            <tr>
              <th align="center" valign="middle"></th>
              <th
                v-for="(th, index) in list[0].data"
                :key="index"
                align="center"
                valign="middle"
              >
                {{ th.date }}
              </th>
            </tr>
            <tr v-for="(tr, index) in list" :key="index">
              <td>
                {{ tr.item }}
              </td>
              <td
                v-for="(tr, index) in tr.data"
                :key="index"
                align="center"
                valign="middle"
              >
                {{ tr.count }}
              </td>
            </tr>
          </table>
        </el-card>
        <!-- 公众号推广统计 -->
        <el-card
          shadow="always"
          :body-style="{ padding: '20px' }"
          v-show="currentName == 'third'"
        >
          <div style="display: flex;align-items: center;font-size: 20px;">
            已关注人数：
            <count-to
              :startVal="startValue"
              :endVal="wechatCount"
              :duration="duration"
              v-if="currentName == 'third'"
              style="color: #409eff;font-size: 26px;border: 1px solid #409eff;padding: 5px 10px;border-radius: 5px;margin: 0 10px;"
            ></count-to>
            人
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
let myChart = null;
import countTo from "vue-count-to";
import {
  orderTotalReport,
  getUserByCompanyId,
  getUserByLableId,
  orderItemReport,
  getWechatCount
} from "../../api/report";
import { companyFind } from "../../api/company";
import { getTagList } from "../../api/tag";
import { getUserList } from "../../api/user";

import * as echarts from "echarts";
export default {
  components: {
    countTo
  },
  data() {
    return {
      // title
      title: "报表标题",
      //最值
      maxData1: "",
      maxData2: "",
      minData1: "",
      minData2: "",
      currentName: "",
      startValue: 0,
      duration: 1000,

      // 默认展示图表
      form: {
        // 日期类型
        dateType: 0,
        dateTimeFor: "",
        // 年份
        year: new Date().getFullYear().toString(),
        // 公司
        companyId: "",
        // 用户
        userId: "",
        // 标签
        lableId: ""
      },
      currentType: 0,
      btnList: ["年度报表", "季度报表", "月度报表"],
      companyId: [],
      lableId: [],
      userIds: [],
      activeName: "first",
      // 接受的数据
      legendData: ["订单金额", "订单数量"],
      list: [],
      wechatCount:0,
      optionDataY: [], // Y轴 订单数量
      optionDataY2: [], // Y轴 订单金额
      optionDataX: [], // X轴 名单
      loading: false,
      option: {
        title: {
          text: "",
          left: "center"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: [], //变
          top: "bottom",
          textStyle: {}
        },
        xAxis: {
          //变
          data: [],
          boundaryGap: false,
          //设置轴线的属性
          axisLine: {
            lineStyle: {}
          },
          // 设置轴线文字样式
          axisLabel: {
            show: true,
            textStyle: {}
          }
        },
        yAxis: [
          {
            type: "value",
            name: "订单数量",
            axisLabel: {
              formatter: "{value}",
              textStyle: {}
            },
            min: this.minData2,
            max: this.maxData2,
            splitNumber: 8, //设置坐标轴的分割段数
            //设置轴线的属性
            axisLine: {
              lineStyle: {}
            }
          },
          {
            type: "value",
            name: "订单金额",
            axisLabel: {
              formatter: "{value}",
              textStyle: {}
            },
            min: this.minData1,
            max: this.maxData1,
            splitNumber: 8, //设置坐标轴的分割段数
            //设置轴线的属性
            axisLine: {
              lineStyle: {}
            }
          }
        ],
        series: [
          {
            name: "订单数量",
            type: "line",
            yAxisIndex: 0,
            label: {
              normal: {
                show: true,
                position: "top",
                textStyle: {
                  //   color: "#fff",
                }
              }
            },
            areaStyle: {
              opacity: 0.4
            },
            emphasis: {
              focus: "series"
            },
            itemStyle: {
              normal: {
                color: "#91cc75"
              }
            },
            data: []
          },
          {
            name: "订单金额",
            type: "line",
            yAxisIndex: 1,
            label: {
              normal: {
                show: true,
                position: "top",
                textStyle: {
                  // color: "#fff",
                }
              }
            },
            areaStyle: {
              opacity: 0.4
            },
            emphasis: {
              focus: "series"
            },
            itemStyle: {
              normal: {
                color: "#ee6666"
              }
            },
            data: []
          }
        ]
      }
    };
  },

  methods: {

    //获取公众号关注人数
    async getWechatCount(){
      const res = await getWechatCount()
      this.wechatCount = res.data
    },
    //图表切换
    switchReport(e) {
      this.currentType = e;
      let month = (new Date().getMonth() + 1).toString();
      let year = new Date().getFullYear().toString();
      // 默认展示图表
      this.form = {
        // 年份
        year: year,
        dateTimeFor: "",
        // 公司
        companyId: "",
        // 用户
        userId: "",
        // 标签
        lableId: ""
      };
      if (e == 2) {
        this.form.dateTimeFor = month;
      }
      this.form.dateType = e;
    },

    // 切换顶部tab栏
    tabClick(e) {
      this.currentName = e.name;
      e.name == "second" ? this.getOrderItemReport() : this.getData(this.form);
    },

    // 检测项目报表
    getOrderItemReport() {
      orderItemReport(this.form).then(res => {
        if (res.data) {
          this.list = res.data;
          // 清空上个图表的数据
          this.optionDataY = [];
          this.optionDataY2 = [];
          this.optionDataX = [];
          let lists = this.list[0].data;
          this.optionDataX = lists.map(v => {
            return v.date;
          });
          let arr = [];
          this.list.forEach((item, index) => {
            let arr2 = [];
            item.data.forEach(v => {
              arr2.push(v.count);
            });
            arr.push(arr2);
          });
          this.option.series = [];
          arr.forEach(v => {
            this.option.series.push({
              name: "",
              type: "line",
              yAxisIndex: 0,
              label: {
                normal: {
                  show: true,
                  position: "top",
                  textStyle: {}
                }
              },
              areaStyle: {
                opacity: 0.4
              },
              emphasis: {
                focus: "series"
              },
              data: v
            });
          });
          this.list.forEach((v, index) => {
            this.option.legend.data.push(v.item);
            this.option.series.forEach((j, inx) => {
              if (index == inx) {
                j.name = v.item;
              }
            });
          });
          //   使用刚指定的配置项和数据显示图表
          this.option.title.text = `检测项目报表`;
          this.option.xAxis.data = this.optionDataX; //x轴
          myChart.setOption(this.option, true);
        }
      });
    },

    getUserName(p) {},

    // 获取标签列表
    async getTagPageList() {
      let data = {
        pageIndex: 1,
        size: 999
      };
      let result = await getTagList(data);
      if (result.code == 200 && result.data) {
        const { items } = result.data;
        this.lableId = items.map(v => {
          return {
            value: v.id,
            label: v.labelName
          };
        });
        this.lableId.unshift({
          value: 0,
          label: "全部"
        });
      } else {
        this.lableId = [];
      }
    },

    // 用户列表模糊查询
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this._getUserList(query);
        }, 200);
      } else {
        this.userIds = [];
      }
    },

    // 获取用户列表数据
    async _getUserList(e) {
      let res = await getUserList({ name: e, size: 999, pageIndex: 1 });
      if (res.code == 200) {
        let { items } = res.data;
        this.userIds = items.map(v => {
          return {
            value: v.wxid,
            label: v.wxName
          };
        });
      } else {
        this.$message.error(res.message);
      }
      this.loading = false;
    },

    // 根据公司获取当前用户
    async _getUserByCompanyId(companyId) {
      let res = await getUserByCompanyId({ companyId });
      if (res.data) {
        this.userIds = res.data.map(v => {
          return {
            value: v.key,
            label: v.value
          };
        });
      }
    },

    // 根据标签获取当前用户
    async _getUserByLableId(lableId) {
      let res = await getUserByLableId({ lableId });
      if (res.data) {
        this.userIds = res.data.map(v => {
          return {
            value: v.key,
            label: v.value
          };
        });
      }
    },

    // 获取数据
    getData(data) {
      // console.log(data);
      orderTotalReport(data).then(res => {
        if (res.code == 200) {
          this.list = res.data;
          this.option.series = [
            {
              name: "订单数量",
              type: "line",
              yAxisIndex: 0,
              label: {
                normal: {
                  show: true,
                  position: "top",
                  textStyle: {}
                }
              },
              areaStyle: {
                opacity: 0.4
              },
              emphasis: {
                focus: "series"
              },
              itemStyle: {
                normal: {
                  color: "#91cc75"
                }
              },
              data: []
            },
            {
              name: "订单金额",
              type: "line",
              yAxisIndex: 1,
              label: {
                normal: {
                  show: true,
                  position: "top",
                  textStyle: {
                    // color: "#fff",
                  }
                }
              },
              areaStyle: {
                opacity: 0.4
              },
              emphasis: {
                focus: "series"
              },
              itemStyle: {
                normal: {
                  color: "#ee6666"
                }
              },
              data: []
            }
          ];
          // 清空上个图表的数据
          this.optionDataY = [];
          this.optionDataY2 = [];
          this.optionDataX = [];
          this.list.forEach(item => {
            this.optionDataX.push(item.item1);
            this.optionDataY.push(item.item2);
            this.optionDataY2.push(item.item3);
          });

          // 计算最值
          this.initData(this.optionDataY2, this.optionDataY);
          //   使用刚指定的配置项和数据显示图表
          // this.option.title.text = `${this.form.year}年 ${this.title}`;
          this.option.title.text = `订单金额报表`;
          this.option.legend.data = this.legendData; // 图例
          this.option.xAxis.data = this.optionDataX; //x轴
          this.option.series[0].data = this.optionDataY2; // Y轴
          this.option.series[1].data = this.optionDataY; // Y2轴
          myChart.setOption(this.option, true);
          this.$forceUpdate();
        }
      });
    },
    // 计算最值
    initData(y2, y) {
      // 获取最大值方法
      function calMax(arr) {
        arr = arr.filter(item => {
          return item != "";
        });
        var max = Math.max.apply(null, arr); // 获取最大值方法
        var maxint = Math.ceil(max / 5); // 向上以5的倍数取整
        var maxval = maxint * 5 + 5; // 最终设置的最大值
        return maxval; // 输出最大值
      }
      // 获取最小值方法
      function calMin(arr) {
        arr = arr.filter(item => {
          return item != "";
        });
        var min = Math.min.apply(null, arr); // 获取最小值方法
        var minint = Math.floor(min / 1); // 向下以1的倍数取整
        var minval = minint * 1 - 5; // 最终设置的最小值
        return minval; // 输出最小值
      }
      // 调用方法，获取数据的最大值&最小值
      this.maxData1 = calMax(y);
      this.maxData2 = calMax(y2);
      this.minData1 = calMin(y);
      this.minData2 = calMin(y2);
    },

    // 获取公司列表
    async _companyFind() {
      let parm = {
        searchKey: this.inputName,
        pageIndex: 1,
        pageSize: 9999
      };
      let res = await companyFind(parm);
      if (res.data) {
        const { items } = res.data;
        let newCompany = items.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
        newCompany.unshift({
          value: 0,
          label: "全部"
        });
        this.companyId = newCompany;
      } else {
        this.CompanyData = [];
      }
    }
  },
  watch: {
    form: {
      handler(newV) {
        if (this.activeName == "first") {
          this.getData(this.form);
        } else {
          this.getOrderItemReport(this.form);
        }
      },
      deep: true
    },
    "form.companyId"(val) {
      if (val) {
        this.form.lableId = "";
        this.userIds = [];
        this.form.userId = "";
      }
      this._getUserByCompanyId(this.form.companyId);
    },
    "form.lableId"(val) {
      if (val) {
        this.form.companyId = "";
        this.userIds = [];
        this.form.userId = "";
      }
      this._getUserByLableId(this.form.lableId);
    }
  },

  created() {
    this.getData(this.form); // 获取数据
    this._companyFind(); //获取公司数据
    this.getTagPageList();
    this.getWechatCount()
  },
  mounted() {
    // 基于准备好的dom，初始化echarts实例
    myChart = echarts.init(document.getElementById("main"));

    this.$nextTick(() => {
      myChart.resize();
    });
    // 浏览器窗口变 ecahrts图表变
    window.addEventListener("resize", () => {
      myChart.resize();
    });
  }
};
</script>

<style lang="less" scoped>
.center-w {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  height: 85vh;
  padding: 20px;
  border: 1px solid #ccc;
  margin: 20px;
  .report {
    // box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.25);
    height: 100vh;
    overflow-y: scroll;
    .header {
      padding: 10px 0;
      // border-bottom: 2px solid #e4e7ed;
    }
    .selectTop {
      display: flex;
      // justify-content: center;
      align-items: center;
      // padding: 10px;
      // margin-bottom: 10px;
    }
    .part {
      height: 600px;

      .main {
        width: 100%;
        height: 100% !important;
      }
    }
    .table11_3 table {
      width: 100%;
      margin: 15px 0;
    }
    .table11_3 th {
      background-color: #fff;
      color: #444;
    }
    .table11_3,
    .table11_3 th,
    .table11_3 td {
      font-size: 0.95em;
      text-align: center;
      padding: 5px 35px;
      border-collapse: collapse;
    }
    .table11_3 th,
    .table11_3 td {
      border: 1px solid #3247c0;
      border: 2px inset #ffffff;
    }
    .table11_3 tr {
      // border: 1px solid #ffffff;
    }
    .table11_3 tr:nth-child(odd) {
      background-color: #ffffff;
    }
    .table11_3 tr:nth-child(even) {
      background-color: #ffffff;
    }
  }
}

/deep/ .el-tabs__item {
  height: 50px !important;
  width: 140px;
  line-height: 50px;
  font-size: 16px;
  font-weight: 700;
}

.el-tag {
  margin: 0 5px;
}
.el-tag:hover {
  cursor: pointer;
}
</style>
